package com.th.coupon.schedule;

import com.th.coupon.common.vo.TemplateRule;
import com.th.coupon.dao.CouponTemplateDao;
import com.th.coupon.entity.CouponTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务
 * @author 涂航
 */
@Slf4j
@Component
public class ScheduledTask {

    /**
     * 优惠卷模板持久层
     */
    private final CouponTemplateDao couponTemplateDao;
    @Autowired
    public ScheduledTask(CouponTemplateDao couponTemplateDao) {
        this.couponTemplateDao = couponTemplateDao;
    }

    /**
     * 自动清除（下线）过期的优惠卷模板 每小时执行一次
     * {@Scheduled(cron = "0 0 0-23 * * ? *")}
     */
    @Scheduled(fixedRate = 60 * 60 *1000)
    public void offlineCouponTemplate(){
        log.info("Start to Expire CouponTemplate !!!");
        //查询未过期的优惠卷模板
        List<CouponTemplate> allByExpired = couponTemplateDao.findAllByExpired(false);
        if(CollectionUtils.isEmpty(allByExpired)){
           log.info("Done To Expire CouponTemplate !!!");
            return;
        }

        Date currentDate = new Date();

        List<CouponTemplate> expireTemplates = new ArrayList<>(allByExpired.size());

        allByExpired.forEach(t->{
            //根据优惠卷模板规则中的过期规则效验模板是否过期
            TemplateRule rule = t.getRule();
            if(rule.getExpiration().getDeadline() < currentDate.getTime()){
                t.setExpired(true);
                expireTemplates.add(t);
            }
        });
        //判断过期的优惠卷模板集合是否为空
        if(CollectionUtils.isNotEmpty(expireTemplates)){
            log.info("Expired CouponTemplate Num : {}",couponTemplateDao.saveAll(expireTemplates));
        }

        log.info("Done To Expire CouponTemplate !!!");
    }

}
